// mircoApp/horizon/serviceDevice/serviceDevice.js
const app = getApp();
var buleHandle = require("../../../utils/horizonBule");

Page({
  behaviors: [buleHandle],
  /**
   * 页面的初始数据
   */
  data: {
    deviceList: [],
    page: 1,
    current_page: 0,
    last_page: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getData() {
    let urlStr = app.getNetAddresss("plugin.horizon.frontend.machine-use.machineUseLog");
    app._getNetWork({
      url: urlStr,
      data: {
        page: this.data.page
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res)
          this.setData({
            deviceList: res.data.data,
            current_page: res.data.current_page,
            last_page: res.data.last_page
          })
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 查看已经连接的设备
  tapLook(e) {
    let code = e.currentTarget.dataset.id;
    console.log(code)
    let that = this;
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log(res)
        that.get_getBluetoothDevices(code);
      },
      fail: (err) => {
        if (res.errCode === 10001) {
          wx.showModal({
            title: '请开启蓝牙',
          })
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            that.get_getBluetoothDevices(code);
          })
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: res.errMsg,
          })
        }
      }
    })

  },
  get_getBluetoothDevices(code) {
    let that = this;
    wx.getBluetoothDevices({
      success: (res) => {
        console.log(res)
        let device = res.devices;
        let list = device.filter((item) => {
          return item.name == 'HUIYANXINGDONG' && item.advertisData
        })
        if (list.length <= 0) {
          app.tips('没有连接该设备蓝牙')
          return
        }
        for (let i = 0; i < list.length; i++) {
          if (that.mac(list[i].advertisData) == code) {
            console.log(list[i], '对应的设备' + code)
            that.reenter(code, list[i].deviceId, list[i].advertisServiceUUIDs[0])
          }
        }
      }
    })
  }
})